
package com.android.ContactPresets;

import android.app.Activity;
import android.app.AlarmManager;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioSystem;
import android.net.Uri;
import android.os.Bundle;
import android.os.IServiceManager;
import android.os.ServiceManagerNative;
import android.os.SystemClock;
import android.telephony.IPhone;
import android.telephony.PhoneNumberUtils;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Menu.Item;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
/**
 * @author Sridhar Jagannathan (sxjthefirst@gmail.com)
 */
public class ContactsView extends Activity {
	private EditText mNameText;
	private EditText mMobileText;
	private EditText mHomeText;
	private EditText mEmailText;
	private EditText mPrefixText;
	private EditText mPreset1Text;

	private TableLayout mPresetsTable;

	private Long mRowId;
	private ContactsDbAdapter mDbHelper;

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.contacts_view);

		mNameText = (EditText) findViewById(R.id.namev);
		mHomeText = (EditText) findViewById(R.id.homev);
		mMobileText = (EditText) findViewById(R.id.mobilev);
		mPrefixText = (EditText) findViewById(R.id.prefixv);
		mEmailText = (EditText) findViewById(R.id.emailv);
		mPreset1Text = (EditText) findViewById(R.id.preset1v);


		mPresetsTable =(TableLayout)findViewById(R.id.presetTable);

		mHomeText.setOnClickListener(new View.OnClickListener(){
			public void onClick(View view) {
				String tmp=mHomeText.getText().toString().trim();
				if (!tmp.equals(""))
					makeCall(tmp);
			}
		});
		mMobileText.setOnClickListener(new View.OnClickListener(){
			public void onClick(View view) {
				String tmpstr=mMobileText.getText().toString().trim();
				if (!tmpstr.equals(""))
					makeCall(tmpstr);
			}
		});
		mEmailText.setOnClickListener(new View.OnClickListener(){
			public void onClick(View view) {
				String tmp=mEmailText.getText().toString().trim();
				if (!tmp.equals(""))
					sendEmail(tmp);
			}
		});

		mDbHelper = new ContactsDbAdapter(this);
		mDbHelper.open();

		// IF resuming after a freeze or pause
		mRowId = icicle != null ? icicle.getLong(ContactsDbAdapter.KEY_ROWID): null;
		// ELSE
		if (mRowId == null) {
			Bundle extras = getIntent().getExtras();
			mRowId = extras != null ? extras.getLong(ContactsDbAdapter.KEY_ROWID) : null;
		}
		populateFields();
	}

	private void sendEmail(String to)
	{
		try
		{
			Uri uri1 = Uri.parse("mailTo:"+ to);
			Intent i = new Intent(Intent.DEFAULT_ACTION,uri1);
			startActivity(i);
		}catch (ActivityNotFoundException anfe){
			showAlert(getText(R.string.app_name),R.drawable.contactsicon,
					getText(R.string.not_supported),getText(R.string.ok),true);
		}catch(Exception e)	{}
	}

	/**
	 * Attempts to make a call to the number after processing any presets
	 * @param number the number to call.
	 */

	private void makeCall(String number) {
		String postdial=null;
		String presetsText[] = mPreset1Text.getText().toString().split(":");

		for (int i = 0; i < presetsText.length; i++) {
			String presets[] = presetsText[i].split("-");

			if (presets[0].equals("Timeout") ) {
				// Convert the timeout (in seconds) to milliseconds and pass it to the alarm
				startTimeout(Long.parseLong(presets[1])*1000);
			}

			if (presets[0].equals("Speaker")) {
				boolean mode = Boolean.parseBoolean(presets[1]);
				AudioSystem.speakerphone(mode);
			}
			if (presets[0].equals("IVS")) {
				postdial=  PhoneNumberUtils.WAIT + presets[1];		
			}
		}

		// Get the phone service
		IPhone phoneService = null;
		try {
			IServiceManager sm = ServiceManagerNative.getDefault();
			phoneService = IPhone.Stub.asInterface(sm.getService("phone"));
		} catch (Exception e) {
		}
		;
		// Add prefix and post-dial sequences to the number
		number = mPrefixText.getText().toString()+ number + postdial;
		try {
			phoneService.call(number);
		} catch (Exception e) {
		}
		;
	}

	/**
	 * Populate the text fields with data if this is an update.
	 */
	private void populateFields() {
		if (mRowId != null) {
			Cursor note = mDbHelper.fetchContact(mRowId);

			startManagingCursor(note);

			mNameText.setText(note.getString(note
					.getColumnIndex(ContactsDbAdapter.KEY_NAME)));
			mHomeText.setText(note.getString(note
					.getColumnIndex(ContactsDbAdapter.KEY_HOME)));
			mMobileText.setText(note.getString(note
					.getColumnIndex(ContactsDbAdapter.KEY_MOBILE)));
			mPrefixText.setText(note.getString(note
					.getColumnIndex(ContactsDbAdapter.KEY_PREFIX)));
			mEmailText.setText(note.getString(note
					.getColumnIndex(ContactsDbAdapter.KEY_EMAIL)));
			String tmp=note.getString(note.getColumnIndex(ContactsDbAdapter.KEY_PRESET1));
			mPreset1Text.setText(tmp);
			if (!tmp.trim().equals(""))
			{
				String[] presets=tmp.split(":");
				mPresetsTable.removeAllViews();
				for (int i=0; i<presets.length;i++)
				{
					String[] presetsPair = presets[i].split("-");

					TableRow tr =new TableRow(this);
					tr.setOrientation(TableRow.HORIZONTAL );
					TextView tv=new TextView(this);
					tv.setText(presetsPair[0]);
					EditText et=new EditText(this);
					et.setEnabled(false);
					et.setTextSize(12);
					et.setText(presetsPair[1]);
					et.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT,
							ViewGroup.LayoutParams.FILL_PARENT));
					tr.addView(tv,new TableRow.LayoutParams( TableRow.LayoutParams.FILL_PARENT,
							TableRow.LayoutParams.FILL_PARENT) );
					tr.addView(et,new TableRow.LayoutParams( TableRow.LayoutParams.FILL_PARENT,
							TableRow.LayoutParams.FILL_PARENT) );
					mPresetsTable.addView(tr,new TableLayout.LayoutParams(
							TableLayout.LayoutParams.FILL_PARENT,
							TableLayout.LayoutParams.FILL_PARENT ));
				}

			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, Menu.FIRST, R.string.call);
		menu.add(0, Menu.FIRST+1, R.string.textmsg);
		menu.add(0, Menu.FIRST+2, R.string.mms);
		menu.add(0, Menu.FIRST+3, R.string.videocall);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, Item item) {
		String tmp;
		switch (item.getId()) {
		case Menu.FIRST: //Call
			tmp=mHomeText.getText().toString().trim(); //Get home number
			if (tmp.equals("")) // if home number is blank
			{
				tmp=mMobileText.getText().toString().trim(); // Get mobile number
			}
			if (!tmp.equals(""))//Check if either number has been entered
				makeCall(tmp);
			return true;
		case Menu.FIRST +1: //Text Message
			tmp=mHomeText.getText().toString().trim(); //Get home number
			if (tmp.equals("")) // if home number is blank
			{
				tmp=mMobileText.getText().toString().trim(); // Get mobile number
			}
			if (!tmp.equals(""))//Check of either number has been entered
			{
				//TODO Currently there is no SMS editor/sender application in Android 
				// when one is added try to open it here. 
				// The below code  if uncommented.will send a dummy message
				/*
				SmsManager smsmgr= SmsManager.getDefault();
				smsmgr.sendTextMessage(tmp, null, tmp, null, null, null);
				Toast.makeText(this,"Message sent", Toast.LENGTH_SHORT); 
				 */

				//Not supported alert.
				showAlert(getText(R.string.app_name),R.drawable.contactsicon,
						getText(R.string.not_supported),getText(R.string.ok),true);
			}
			return true;
		case Menu.FIRST +2: //Multimedia Message
			tmp=mHomeText.getText().toString().trim(); //Get home number
			if (tmp.equals("")) // if home number is blank
			{
				tmp=mMobileText.getText().toString().trim(); // Get mobile number
			}
			if (!tmp.equals(""))// if one of the numbers has been entered
			{
				//TODO Currently there is no MMS editor/sender application in Android 
				// when one is added try to open it here. 
				// The below code  if uncommented.will send a dummy message to port 80
				/*
				SmsManager smsmgr= SmsManager.getDefault();
				smsmgr.sendDataMessage(tmp, null,(short)80, tmp.getBytes(), null, null, null);
				Toast.makeText(this,"Message sent", Toast.LENGTH_SHORT); 
				*/
				showAlert(getText(R.string.app_name),R.drawable.contactsicon,
						getText(R.string.not_supported),getText(R.string.ok),true);
			}
			return true;
		case Menu.FIRST +3: //Video Call
			tmp=mHomeText.getText().toString().trim(); //Get home number
			if (tmp.equals("")) // if home number is blank
			{
				tmp=mMobileText.getText().toString().trim(); // Get mobile number
			}
			if (!tmp.equals(""))//Check of either number has been entered
			{
				showAlert(getText(R.string.app_name),R.drawable.contactsicon,
						getText(R.string.not_supported),getText(R.string.ok),true);
			}
			return true;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	protected void onFreeze(Bundle outState) {
		super.onFreeze(outState);
		outState.putLong(ContactsDbAdapter.KEY_ROWID, mRowId);
	}

	@Override
	protected void onResume() {
		super.onResume();
		populateFields();

	}

	@Override
	protected void onPause() {
		super.onPause();
		;
	}

	/**
	 * starts an timer to prompt user when a call goes beyond timeout milliseconds 
	 * @param timeout - milliseconds to wait before prompting user.
	 */
	private void startTimeout(long timeout)
	{
		// Schedule the alarm!
		long firstTime = SystemClock.elapsedRealtime() + timeout;
		AlarmManager am  = (AlarmManager)getSystemService(ALARM_SERVICE);
		Intent intent = new Intent(this, TimeoutIntentReceiver.class);
		am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, timeout, intent);
	}

}
